package serialize;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class GsonUtils {

    private static final Gson sGson = new Gson();

    public static String toGsonString(Object obj) {
        return sGson.toJson(obj);
    }

    /**
     * json字符串转对象
     *
     * @param s   the string from which the object is to be deserialized
     * @param c   the class of T, 如果有默认的无参构造函数，则返回值不为空
     * @param <T> the type of the desired object
     * @return
     */
    public static <T> T fromJson(String s, Class<T> c) {
        T bean = null;
        if (c != null && s != null) {
            try {
                bean = new Gson().fromJson(s, c);
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
                try {
                    /**
                     * 如果有默认的无参构造函数，则返回值不为空
                     */
                    bean = c.newInstance();
                } catch (InstantiationException e1) {
                    e1.printStackTrace();
                } catch (IllegalAccessException e1) {
                    e1.printStackTrace();
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return bean;
    }
}
